import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message, Modal, Space } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AddSearch from './components/addSearch';
import UpdateSearch from './components/updateSearch';
import DetailSearch from './components/searchDetail';
import { searchTypeList } from './data';
import { handleLogisticsSearch, logisticsSearchPages } from './service';
import { useModel } from 'umi';
import { Auths } from '@/utils/typings.d';
// import AdvancePayment from '@/pages/LogisticsSearch/components/AdcancePayment';
// import styles from './style.less';

const LogisticsSearchTableList: React.FC<any> = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.logistics || []) : new Set();
  const ifCreate = auths.has(Auths.CREATE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifDelete = auths.has(Auths.DELETE);
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const [addSearchVisible, setAddSearchVisible] = useState<boolean>(false);
  const [updateVisible, setUpdateVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [getId, setGetId] = useState<string>('');

  const handleExit = async (id: string) => {
    const hide = message.loading('正在删除');
    const res = await handleLogisticsSearch(id);
    hide();
    if (res.code == 0) {
      message.success('删除成功');
      if (actionRef.current?.reloadAndRest) {
        actionRef.current?.reloadAndRest();
      }
      return true;
    } else {
      message.error(`删除失败！${res.message}`);
      return false;
    }
  };

  const columns: ProColumns<searchTypeList>[] = [
    {
      title: '物流公司名称',
      dataIndex: 'logisticsName',
      ellipsis: true,
      hideInSearch: false,
      render: (_, record) => {
        if (record.logisticsConfig) return record?.logisticsConfig.name;
        return '-';
      },
    },
    {
      title: '目的地',
      dataIndex: 'area',
      ellipsis: true,
      hideInSearch: false,
      render: (_, record) => {
        let areaSum = '';
        record.area.map((item: string) => {
          areaSum += item + '/';
        });
        if (areaSum.endsWith('/')) {
          areaSum = areaSum.substring(0, areaSum.length - 1);
        }
        return areaSum;
      },
    },
    {
      title: '最低价格',
      dataIndex: '',
      ellipsis: true,
      hideInSearch: true,
      render(_, entity) {
        return <div>{(entity.lowCharge / 100).toFixed(2)} 元</div>;
      },
    },
    {
      title: '操作',
      dataIndex: 'options',
      ellipsis: true,
      width: '150px',
      hideInSearch: true,
      render: (_, record) => {
        const onClickExitPark = () => {
          Modal.confirm({
            title: `是否要删除此条物流信息`,
            content: (
              <>
                <p>
                  物流公司：{record.logisticsConfig.name} 目的地：{record.area.toString()}
                </p>
                <p>删除之后无法撤回，请谨慎操作！</p>
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleExit(record._id);
            },
            centered: true,
            width: '400px',
            style: { height: '20vw' },
          });
        };
        return (
          <Space size="small">
            {ifModify && (
              <a
                onClick={() => {
                  setGetId(record._id);
                  setUpdateVisible(true);
                }}
              >
                修改
              </a>
            )}
            <a
              onClick={() => {
                setGetId(record._id);
                setDetailVisible(true);
              }}
            >
              详情
            </a>
            {ifDelete && <a onClick={onClickExitPark}>删除</a>}
          </Space>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<searchTypeList>
        scroll={{ x: true }}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<any>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        toolBarRender={() => [
          ifCreate && (
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setAddSearchVisible(true);
              }}
            >
              添加
            </Button>
          ),
        ]}
        params={{
          sorter,
        }}
        tableAlertRender={() => false}
        request={async (params = {}) => {
          const { current: page, pageSize, area, logisticsName, ...filter } = params;
          const res = await logisticsSearchPages({
            page: String(page),
            pageSize: String(pageSize),
            area,
            logisticsName,
            ...filter,
          });
          return res;
        }}
        columns={columns}
        rowSelection={false}
        pagination={{
          defaultPageSize: 10, //每页显示的数量
          size: 'default', //页数显示的样式
          showQuickJumper: true, //默认显示，两页以上才显示，跳转到指定页数
          showSizeChanger: true,
        }} //默认显示，多页以上才显示，让每页显示指定数据量的数据
      />
      {updateVisible && (
        <UpdateSearch
          id={getId}
          visible={updateVisible}
          unVisible={() => setUpdateVisible(false)}
          reloadFunc={() => actionRef.current?.reload()}
        />
      )}
      {detailVisible && (
        <DetailSearch
          id={getId}
          visible={detailVisible}
          unVisible={() => setDetailVisible(false)}
        />
      )}
      {addSearchVisible && (
        <AddSearch
          visible={addSearchVisible}
          unVisible={() => setAddSearchVisible(false)}
          reloadFunc={() => actionRef.current?.reload()}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default LogisticsSearchTableList;
